package com.lc.boot.initializer;

import com.lc.boot.config.MyAppConfig;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * @author liuc
 * @date 2021/5/2
 * @description java代码实现web.xml  WebApplicationInitializer
 **/
public class MyWebApplicationInitializer implements LcWebApplicationInitializer {
    @Override
    public void startUp(ServletContext servletContext) throws ServletException {
        System.out.println("MyWebApplicationInitializer come in...");
        //通过注解的方式初始化Spring的上下文
        AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
        //注册spring的配置类（替代传统项目中xml的configuration）
        ac.register(MyAppConfig.class);
        //? 疑问,什么时候会被刷新上下文呢,创建bean对象呢?
        //ac.refresh();
        //ac.refresh方法会在DispatcherServlet的init方法中调用

        // Create and register the DispatcherServlet
        //基于java代码的方式初始化DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(ac);
        ServletRegistration.Dynamic registration = servletContext.addServlet("/", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/");
    }
}
